import sys,os
from subprocess import call

matlock = "/scratch/project/qaafi-cnafs/jingping/software/miniconda3/bin/matlock"
samtools = "/scratch/project/qaafi-cnafs/jingping/software/miniconda3/bin/samtools"
assvis = "/scratch/project_mnt/S0030/jingping/software/3d-dna/visualize/run-assembly-visualizer.sh"
agp2assamble = "/scratch/project_mnt/S0030/jingping/software/juicebox_scripts/juicebox_scripts/agp2assembly.py"
py2 = "/scratch/project_mnt/S0030/jingping/software/Python-2.7.10/bin/python2"
bwa = "/scratch/project/qaafi-cnafs/jingping/software/miniconda3/bin/bwa"
R2 = "/scratch/project_mnt/S0030/jingping/01.Banana_genome_project/15.ragtag2hic/fastq/HiC_R2.fastq.gz"
R1 = "/scratch/project_mnt/S0030/jingping/01.Banana_genome_project/15.ragtag2hic/fastq/HiC_R1.fastq.gz"
#ref = "/scratch/project_mnt/S0030/jingping/01.Banana_genome_project/15.ragtag2hic/genome.fa"
bam = "bwa_align.bam"
ref = sys.argv[1]
agp = sys.argv[2]
thread = sys.argv[3]
cmd = f"{bwa} index {ref}\n"
cmd += f"{bwa} mem -SP5M -t {thread} {ref} {R1} {R2} | samtools  view  -hF  268 - | samtools sort -n -@ {thread} -o {bam} -T tmp.align \n"
cmd += f"{samtools} index {bam}\n"
cmd += f"{matlock} bam2 juicer {bam} merged_nodups.txt\n"
cmd += f"{py2} {agp2assamble} {agp} groups.assembly\n"
cmd += f"bash {assvis} -q 1 -p true groups.assembly merged_nodups.txt"
print(cmd)
#cmd_sh = "head -n 15 /scratch/project_mnt/S0030/jingping/01.Banana_genome_project/15.ragtag2hic/ragtag2hic_test/filterbam.slum > rattag2hic.slum\n"
cmd_sh = f'''echo "#!/bin/bash --login
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task={thread}
#SBATCH --mem=100G
#SBATCH --job-name=allhic
#SBATCH --time=40:00:00
#SBATCH --partition=general
#SBATCH --account=a_qaafi_genomics
#SBATCH -o allhic.slurm.out
#SBATCH -e allhic.slurm.error" >> rattag2hic.slum
'''

cmd_sh += f"echo \"{cmd}\" >> rattag2hic.slum\n"
cmd_sh += "sbatch rattag2hic.slum"
call(cmd_sh, shell=True)
# for i in cmd.split("\n"):
#     #print(i)
#     s = call(i, shell=True)
#     if s != 0:
#         print("error happened...cmd \"%s\" "%(i.strip()))
#         exit(0)
